package com.softserveinc.lahire.handlers;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Date;

import com.softserveinc.lahire.builders.HTTPWorker;
import com.softserveinc.lahire.builders.Request;
import com.softserveinc.lahire.builders.ResponseDirector;
import com.softserveinc.lahire.builders.SimpleResponseBuilder;
import com.softserveinc.lahire.configurator.Configurator;

/**
 * 
 * Class, that handle HTTP request to folders returning simple HTML page with
 * requested directory index. Navigation allowed.
 * 
 * File/Folders can be hidden from this index, by setting 'hidden' NTFS flag.
 * 
 * @author Pavlo Lozovskiy
 * 
 */

public class DirectoryHandler implements Handler {
	private Handler parent = null;

	public void setParent(Handler parent) {
		this.parent = parent;
	}

	public Handler getParent() {
		return parent;
	}

	public void handle(Request request) throws IOException {

		// Set content type for directory list
		

		byte[] buffer = null;
		File file = new File(request.getRecoursePath());
		if ((Boolean) Configurator.getInstance().getObjectByTag(
				"directoryBrowsing")
				&& file.isDirectory()) {

			
			if (file.exists()) {
				request.setContentType(Configurator.mimeType.get("html"));
				
				buffer = constructTemplate(request.getRecoursePath(), file,
						request.getUrl(), request.getHost()).toString()
						.getBytes();

			
				
				SimpleResponseBuilder simpleResponseBuilder = new SimpleResponseBuilder();
				
				
				
				HTTPWorker.responseDirector.setResponseBuilder(simpleResponseBuilder);			
				HTTPWorker.responseDirector.constructResponse(buffer, request.getContentType(),HttpURLConnection.HTTP_OK);
			
			} else {
				System.out.println("File cannot be found");
			}
		} else {
			if (parent != null)
				parent.handle(request);
		}
		//return buffer;

	}

	private StringBuilder constructTemplate(String path, File file, String url,
			String host) {

		StringBuilder htmlTemplate = new StringBuilder();
		// String parent = url.replaceAll("[A-z,0-9]+/$", "");
		String parent = url.replaceAll("" + file.getName() + "+/$", "");

		htmlTemplate.append("<html><Head><Title>Index of " + url
				+ "</Title></head><body>"); // Dynamic
		htmlTemplate.append("<h1>Index of " + url + "</h1><hr>"); // Dynamic
		htmlTemplate
				.append("<table id=\"Index\" CELLSPACING=\"6\"><thead><th>Name</th>");
		htmlTemplate
				.append("<th>Last modified</th><th>Size</th><th>Type</th></thead>");
		htmlTemplate.append("<tbody><tr><td>" + BACK_IMG + "<a href=\""
				+ parent + "\">Parent Directory</a></td></tr>"); // Dynamic

		if (file.isDirectory()) {

			File[] childs = file.listFiles();

			for (File child : childs) {
				htmlTemplate.append(insertRow(child));
			}
		}

		htmlTemplate.append("</tbody></table><hr>");
		htmlTemplate.append("<address>Lehire server at " + host
				+ "</address><body></html>"); // Dynamic

		return htmlTemplate;
	}

	private String insertRow(File file) {

		String length = String.valueOf(file.length());
		String lastModifiedDate = new Date(file.lastModified()).toString();
		String hyperlink;
		String row = "";
		String type;
		String icon;

		if (!file.isHidden()) {
			if (file.isDirectory()) {
				type = "Dir";
				icon = FOLDER_IMG;
				length = "-";
				hyperlink = "<a href=\"" + file.getName() + "/\">"
						+ file.getName() + "</a>";
			} else {
				type = "File";
				icon = FILE_IMG;
				hyperlink = "<a href=\"" + file.getName() + "\">"
						+ file.getName() + "</a>";
			}

			row = "<tr><td>" + icon + hyperlink + "</td>";
			row += "<td>" + lastModifiedDate + "</td>"; // Dynamic
														// lastModified()
														// aligned to current
														// date
			row += "<td ALIGN=\"CENTER\">" + length + "</td>"; // Dynamic
																// length()
			row += "<td ALIGN=\"CENTER\">" + type + "</td></tr>"; // Dynamic
																	// type
																	// isDirectory()

		}

		return row;
	}

	/*
	 * Images used to represent file/folder type, have to be located in the
	 * Webroot/icons folder
	 */

	private static final String FOLDER_IMG = "<img src=\"/icons/folder.gif\" alt=\"[DIR]\">   ";
	private static final String BACK_IMG = "<img src=\"/icons/back.gif\" alt=\"[DIR]\">   ";
	private static final String FILE_IMG = "<img src=\"/icons/file.gif\" alt=\"[FILE]\">   ";

}
